<?php


namespace App\Admin\Actions\Import;


use App\Expert;
use Carbon\Carbon;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;

class ExpertImport extends Action
{
    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        $collect = Excel::toCollection(collect([]), $request->file('file'))->first();
        $user = Admin::user();
        if ($user->role_type != 1) {
            return $this->response()->error('没有权限，如有疑问请联系技术人员')->refresh();
        }
        $collect = collect($collect)->map(function ($item) {
            foreach ($item as $key => $value) {
                $item[$key] = trim($value);
            }
            return $item;
        })->filter(function ($item, $key) {
            return !empty($item[0]) && !empty($item[1]) && $key;
        })->values()->map(function ($row, $index) use ($user) {
            return [
                'username' => $row[0],
                'name' => $row[1],
                'company' => $row[2],
                'academic_title' => $row[3],
                'id_card' => $row[4],
                'major' => $row[5],
                'mobile' => $row[6] ?: null,
                'bank_account' => $row[7],
                'bank' => $row[8],
                'password' => Hash::make($row[9] ?: '123456'),
                'role_type' => 3,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
        });
        if ($collect->pluck('username', 'username')->count() < $collect->count()) {
            return $this->response()->error('登陆名重复')->refresh();
        }
        $res = Expert::query()->whereIn('username', $collect->pluck('username'))->pluck('username')->toArray();
        if ($res) {
            $msg = implode(",", $res);
            return $this->response()->swal()->error("登陆名已存在:\n" . $msg)->refresh();
        }
        if ($collect->count()) {
            Expert::query()->insert($collect->all());
        }
        return $this->response()->success('导入成功')->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件')
            ->help('<a target="_blank" href="' . url('/template/expert_template.xls') . '" download="专家导入模板.xls">专家导入模板</a>');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-instagram import-post">批量导入专家</a>
HTML;
    }

}
